var basePath = 'http://catchpage.com/';

// event process
function onMessage(evt) {
    var data = evt.data;
    if (data && data === 'CP_bookmark_destroy') {
        window.close();
    } else {
        try {
            var size = JSON.parse(data);
            var element = document.getElementById('cp');
            element.style.width = size.width + 'px';
            element.style.height = size.height + 'px';
        } catch (e) {
            console.log(e);
        }
    }
}
// bind event
window.addEventListener('message', onMessage, false);

// get information and request add pin page
chrome.tabs.getSelected(null, function(tab) {
    chrome.tabs.executeScript(tab.id, {
        code: 'var desc = CP.getDescription(); desc'
    }, function(results) {
        var description = results && results[0];

        var url = basePath + 'pin?url=' + encodeURIComponent(tab.url) +
            '&title=' + encodeURIComponent(tab.title || '') +
            '&desc=' + encodeURIComponent(description || '') +
            '&s=bookmark&t=' + (+new Date());

        var element = document.createElement('iframe');
        element.id = 'cp';
        element.src = url;
        element.style.display = 'none';
        element.onload = function () {
            document.body.removeChild(document.getElementById('loading'));
            this.style.display = 'block';
        };
        document.body.appendChild(element);
    });
});